#include "VideoStreamer\VideoStreamerFactory.h"
#include <highgui.h>
#include <boost/thread.hpp>
#include <iostream>

bool running = true;
void readKey(void)
{
	std::cout << "Press 'c'+'Enter' to exit..." << std::endl;
	char c;
	do std::cin >> c;
	while (c != 'c');
	running = false;
}

void main(void)
{
	// Configuration parameters
	//std::string uri = "test.avi";
	//std::string uri = "udp://227.0.0.1:1234?multicast=1";
	std::string uri = "udp://127.0.0.1:1234";

	std::string format = "video/x-mjpeg";
	int bitRate = 1e5; // 1e6
	int frameRate = 25; // 25
	int gopSize = 6; //12
	int bFrames = 2;
	int bufferSize = 2e5; // 2e5

	// Open camera frame grabber and video streamer
	CvCapture *capture = cvCaptureFromCAM(0);
	Sleep((DWORD)1e3); // The camera is slow opening. Lets wait for it.
	IVideoStreamer *vs = VideoStreamerFactory::CreateInstance(
		uri, format, cvGetSize(cvQueryFrame(capture)), bitRate, frameRate, gopSize, bFrames, bufferSize);
	vs->OpenVideo();

	// Save video form the camera to the desired file.
	// Captured image memory is borowed from CvCapture. You sould not release it.
	boost::thread thrd(&readKey);
	IplImage *img;
	while(running)
	{
		img = cvQueryFrame(capture);
		cvFlip(img, img, 0);
		vs->Update(img);
		//cvSaveImage("c:\\webcam.jpg", img);
		Sleep((DWORD)1000/frameRate);
	}

	// Release resources. Close framme graber and video streamer.
	vs->CloseVideo();
	delete vs;
	cvReleaseCapture(&capture);
}